<?php

namespace app\index\controller;

use app\admin\service\OssService;
use app\admin\validate\CommonnValidate;
use app\admin\validate\PhotoValidate;
use app\index\diyclass\Interal;
use app\index\diyclass\Task;
use app\index\model\CommentModel;
use app\index\model\PohtoListImage;
use app\index\model\PohtoTagUser;
use app\index\model\PhotoCollWork;
use app\index\model\UserModel;
use app\index\model\FollowModal;
use app\index\model\PohtoType as PohtoTypeModal;
use app\index\model\PhotoList as PhotoListModal;
use app\index\model\Video as VideoModal;
use app\index\model\PhotoColl as PhotoCollModal;
use app\index\model\PhotoLike as PhotoLikeModal;
use app\index\model\PhotoBuy as PhotoBuyModal;
use app\index\model\PohtoUser as PohtoUserModal;
use app\index\model\PohtoInstitution as PohtoInstitutionModal;
use app\index\model\PohtoTag as PohtoTagModal;
use app\index\model\SearchLog as SearchLogModal;
use app\BaseController;
use think\db\Query;
use think\facade\Db;
use think\Request;
use think\Response;
use ZipArchive;

class Photo extends BaseController
{
    protected $middleware = [
        'Auth' => ['except' => ['allcount', 'tab', 'photoReplyUser', 'randList', 'randVideoList', 'allImgList', 'imgList', 'allTag', 'detail', 'list',  'test', 'detailView', 'photoUser', 'institutionList', 'institutuibDetail', 'roleList', 'tagList', 'searchList', 'doDetailInfo', 'downZip']],
        'Openness' => ['only' => ['imgList', 'detail', 'photoReplyUser', 'list', 'randList', 'randVideoList', 'allImgList']],
    ];
    private $feeNum = 3;

    public function tab()
    {
        $sql = new PohtoTypeModal();
        $list = $sql ->order('sort desc')
            ->order('create_at desc')->select();
        return result()->success($list);
    }
    public function staticInfo(Request $request)
    {
        $sql = new PhotoCollModal();
        $whereArr[] = ['userid', '=', $request->user->id];
        $collCount = $sql->where($whereArr)->count();
        $buySql = new PhotoBuyModal();
        $buyCount = $buySql->where($whereArr)->count();
        return result()->success([
            'coll' => $collCount,
            'buy' => $buyCount,
        ]);
    }
    public function allcount()
    {
        $sql = new PhotoListModal();
        $count = $sql->count();
        return result()->success($count);
    }
    public function mycount()
    {
        $params = $this->request->post(['type_id']);
        $whereArr[] = ['releaseid', '=', $this->request->user->id];
        if(isset($params['type_id']) && $params['type_id']) {
            $whereArr[] = ['type_id', '=', $params['type_id']];
        }
        $sql = new PhotoListModal();
        $apply = $sql->where($whereArr)->where('status', 'APPLY')->count();
        $success = $sql->where($whereArr)->where('status', 'SUCCESS')->count();
        $error = $sql->where($whereArr)->where('status', 'ERROR')->count();
        $not_listed = $sql->where($whereArr)->where('status', 'NOT_LISTED')->count();
        $all = $sql->where($whereArr)->count();
        return result()->success([
            'all' => $all,
            'apply' => $apply,
            'success' => $success,
            'error' => $error,
            'not_listed' => $not_listed,
        ]);
    }
    public function myList()
    {
        $params = $this->request->post(['current', 'status', 'size', 'type_id', 'author_id', 'institution_id', 'keyword', 'tags', 'order', 'orderType', 'userList']);
        $sql = new PhotoListModal();
        $whereArr[] = ['releaseid', '=', $this->request->user->id];
        $whereOr = [];
        $haswhereArr = [];
        if(isset($params['status']) && $params['status']) {
            $whereArr[] = ['status', '=', $params['status']];
        }
        if(isset($params['type_id']) && $params['type_id']) {
            $whereArr[] = ['type_id', '=', $params['type_id']];
        }
        if(isset($params['author_id']) && $params['author_id']) {
            $whereArr[] = ['author_id', '=', $params['author_id']];
        }
        if(isset($params['keyword']) && $params['keyword']) {
            $whereArr[] = ["name", "LIKE", '%'.$params['keyword'].'%'];
            $log = new SearchLogModal();
            $logInfo = $log->where('text', $params['keyword'])->findOrEmpty();
            if($logInfo->isEmpty()) {
                $log->save([
                    'text' => $params['keyword'],
                    'count' => 1
                ]);
            } else {
                $logInfo->count = $logInfo->count + 1;
                $logInfo->save();
            }
        }
        if(isset($params['tags']) && $params['tags']) {
            foreach($params['tags'] as $item){
                $whereOr[] = ["tags", "find in set", $item];
            }
        }
        $condition = isset($params['institution_id']) && $params['institution_id'];
        if($condition) {
            $haswhereArr[] = ['institution_id', '=', $params['institution_id']];
        }
        $orderArr = $this->getOrder($params);
        $list = $sql
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })
            ->where($whereArr)
            ->when($condition, function ($query) use($haswhereArr) {
                $query->where('author_id', 'IN', function ($query) use($haswhereArr) {
                    $query->table('car_photo_user')->where($haswhereArr)->field('id');
                });
            })
            ->with(['tanName', 'userInfo'])
            ->withCount(['like', 'coll', 'buy'])
            ->order($orderArr)
            ->page($params['current'])
            ->limit($params['size'])
            ->select();
        $total = $sql
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })
            ->where($whereArr)
            ->when($condition, function ($query) use($haswhereArr) {
                $query->where('author_id', 'IN', function ($query) use($haswhereArr) {
                    $query->table('car_photo_user')->where($haswhereArr)->field('id');
                });
            })->count();
        foreach ($list as $key => $item) {
            $list[$key]['vip_price'] = floor($item['price'] * config('app.vipDis'));
            if(config('app.imgtype') == 'local') {
                $list[$key]['image_url']= $item['image_path'];
            }
        }
        return result()->success([
            'data' => $list,
            'total' => $total
        ]);
    }
    public function list(Request $request) {
        $params = $this->request->post(['current', 'size', 'id', 'author_id', 'releaseid', 'institution_id', 'keyword', 'tags', 'order', 'orderType', 'userList']);
        $sql = new PhotoListModal();
        $whereArr[] = ['private', '=', 0];
        $whereOr = [];
        $haswhereArr = [];
        if(isset($params['id']) && $params['id']) {
            $whereArr[] = ['type_id', '=', $params['id']];
        }
        if(isset($params['releaseid']) && $params['releaseid']) {
            $whereArr[] = ['releaseid', '=', $params['releaseid']];
        }
        if(isset($params['author_id']) && $params['author_id']) {
            $whereArr[] = ['author_id', '=', $params['author_id']];
        }
        if(isset($params['keyword']) && $params['keyword']) {
            $whereArr[] = ["name", "LIKE", '%'.$params['keyword'].'%'];
            $log = new SearchLogModal();
            $logInfo = $log->where('text', $params['keyword'])->findOrEmpty();
            if($logInfo->isEmpty()) {
                $log->save([
                    'text' => $params['keyword'],
                    'count' => 1
                ]);
            } else {
                $logInfo->count = $logInfo->count + 1;
                $logInfo->save();
            }
        }
        if(empty($request->user) || $request->user['user_type'] != 'VIP') {
//            $whereArr[] = ['tags', 'not like', '%18禁%'];
        }
        if(isset($params['tags']) && $params['tags']) {
            foreach($params['tags'] as $item){
                $whereOr[] = ["tags", "find in set", $item];
            }
        }
        $condition = isset($params['institution_id']) && $params['institution_id'];
        if($condition) {
            $haswhereArr[] = ['institution_id', '=', $params['institution_id']];
        }
        $orderArr = $this->getOrder($params);
        $list = $sql
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })
            ->where($whereArr)
            ->when($condition, function ($query) use($haswhereArr) {
                $query->where('author_id', 'IN', function ($query) use($haswhereArr) {
                    $query->table('car_photo_user')->where($haswhereArr)->field('id');
                });
            })
            ->with(['tanName', 'userInfo'])
            ->withCount(['like', 'coll', 'buy'])
            ->order($orderArr)
            ->page($params['current'])
            ->limit($params['size'])
            ->select();
        foreach ($list as $key => $item) {
            $list[$key]['vip_price'] = floor($item['price'] * config('app.vipDis'));
            if(config('app.imgtype') == 'local') {
                $list[$key]['image_url']= $item['image_path'];
            }
        }
        return result()->success($list);
    }

    public function randVideoList()
    {
        $params = $this->request->post(['size', 'ids']);
        $sql = new VideoModal();
        $whereArr = [];
        if(isset($params['ids']) && $params['ids']) {
            $whereArr[] = ['id', 'not in', $params['ids']];
        }
        $list = $sql
            ->where($whereArr)
            ->orderRaw("rand() , id DESC")
            ->limit($params['size'])
            ->select();
        return result()->success($list);
    }
    public function randList(Request $request)
    {
        $params = $this->request->post(['size', 'ids', 'type_id', 'institution_id', 'author_id', 'tags']);
        $sql = new PhotoListModal();
        $whereArr[] = ['private', '=', 0];
        $whereOr = [];
        $haswhereArr = [];
        if(isset($params['type_id']) && $params['type_id']) {
            $whereArr[] = ['type_id', '=', $params['type_id']];
        }
        if(isset($params['author_id']) && $params['author_id']) {
            $whereArr[] = ['author_id', '=', $params['author_id']];
        }
        if(empty($request->user) || $request->user['user_type'] != 'VIP') {
//            $whereArr[] = ['tags', 'not like', '%18禁%'];
        }
        if(isset($params['ids']) && $params['ids']) {
            $whereArr[] = ['id', 'not in', $params['ids']];
        }
        if(empty($request->user) || $request->user['user_type'] != 'VIP') {
//            $whereArr[] = ['tags', 'not like', '%18禁%'];
        }
        if(isset($params['tags']) && $params['tags']) {
            foreach($params['tags'] as $item){
                $whereOr[] = ["tags", "find in set", $item];
            }
        }
        $condition = isset($params['institution_id']) && $params['institution_id'];
        if($condition) {
            $haswhereArr[] = ['institution_id', '=', $params['institution_id']];
        }
        if(empty($request->user)) {
            $userId = '';
        } else {
            $userId = $request->user->id;
        }
        $list = $sql
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })
            ->where($whereArr)
            ->when($condition, function ($query) use($haswhereArr) {
                $query->where('author_id', 'IN', function ($query) use($haswhereArr) {
                    $query->table('car_photo_user')->where($haswhereArr)->field('id');
                });
            })
            ->with(['tanName', 'userInfo', 'child','coll' => function(Query $query) use ($userId) {
                $query->where('userid', $userId);
            },
                'buy' => function(Query $query) use ($userId) {
                    $query->where('userid', $userId);
                },
                'like' => function(Query $query) use ($userId) {
                    $query->where('userid', $userId);
                }])
            ->withCount(['like', 'coll', 'buy', 'comment'])
            ->orderRaw("rand() , id DESC")
            ->limit($params['size'])
            ->select();
        foreach ($list as $key => $item) {
            $item->vip_price = floor($item['price'] * config('app.vipDis'));
            $item->is_like = $item->like ? true : false;
            $item->is_buy = $item->buy ? true : false;
            $item->is_coll = $item->coll ? true : false;
            $item['child'] = $item->child->toArray();
            if(!$item->is_buy) {
                $item['child'] = array_slice($item['child'],0, $this->feeNum);
            }
            if(config('app.imgtype') == 'local') {
                $child = [];
                foreach ($item['child'] as $k => $imgItem) {
                    $imgItem['image_url'] = $imgItem['image_path'];
                    $child[] = $imgItem;
                }
                $item['child'] = $child;
            }
            unset($item->like);
            unset($item->buy);
            unset($item->coll);
        }
        return result()->success($list);
    }

    public function editTag(Request $request)
    {
        $params = $this->request->post(['id', 'tags']);
        if(count($params['tags']) == 0) {
            return result()->fail('新标签不能为空', 500);
        }
        Db::startTrans();
        try {
            foreach ($params['tags'] as $key => $item) {
                $tagSql = new PohtoTagModal();
                $tagInfo = $tagSql->where('name', $item)->findOrEmpty();
                if($tagInfo->isEmpty()) {
                    $tagSql->save(['name' => $item, 'sort' => 1]);
                }
            }
            $sql = new PhotoListModal();
            $info = $sql->with([
                'buy' => function(Query $query) use ($request) {
                    $query->where('userid', $request->user->id);
                }
            ])->find($params['id']);
            if($info->buy <= 0) {
                Db::rollback();
                return result()->fail('请先购买', 500);
            }
            $back = backNewAndDelTags($info['tags'], $params['tags']);
            if(count($back['add']) == 0 && count($back['del']) == 0) {
                Db::rollback();
                return result()->fail('标签无变化', 500);
            }
            $historyInfo = [
                'photo_id' => $params['id'],
                'user_id' => $request->user->id,
                'addTag' => '',
                'delTag' => ''
            ];
            if(count($back['add']) > 0) {
                $historyInfo['addTag'] = implode(",",$back['add']);
            }
            if(count($back['del']) > 0) {
                $historyInfo['delTag'] = implode(",",$back['del']);
            }
            $tagSql = new PohtoTagUser();
            $oldWhere[] = ['photo_id', '=', $params['id']];
            $oldWhere[] = ['user_id', '=', $request->user->id];
            $oldInfo = $tagSql->where($oldWhere)->findOrEmpty();
            if($oldInfo->isEmpty()) {
                $task = new Task($request->user->id, 'ADD_TAG_TASK');
                $task->save();
            }
            $tagSql->save($historyInfo);
            $info->save($params);
            Db::commit();
            return result()->onlySucMsg("修改成功");
        } catch (\Throwable $th) {
            Db::rollback();
            return result()->fail($th->getMessage(), 500);
        }
    }

    public function detail(Request $request)
    {
        $params = $this->request->get(['id']);
        if(!empty($request->user)) {
            $sql = new PhotoListModal();
            $info = $sql->where('id', $params['id'])->with([
                'coll' => function(Query $query) use ($request) {
                    $query->where('userid', $request->user->id);
                },
                'buy' => function(Query $query) use ($request) {
                    $query->where('userid', $request->user->id);
                },
                'like' => function(Query $query) use ($request) {
                    $query->where('userid', $request->user->id);
                },
                'report' => function(Query $query) use ($request) {
                    $query->where('user_id', $request->user->id);
                },
                'userInfo',
                'release'
            ])->withCount(['like', 'report', 'coll', 'buy'])->find();
            $info->like = $info->like ? true : false;
            $info->buy = $info->buy ? true : false;
            $info->coll = $info->coll ? true : false;
        } else {
            $sql = new PhotoListModal();
            $info = $sql->where('id', $params['id'])->with(['userInfo', 'release'])->withCount(['like', 'report', 'coll', 'buy'])->find();
            $info['buy'] = false;
            $info['coll'] = false;
            $info['like'] = false;
            $info['report'] = null;
        }
        if($info->price == 0) {
            $info->buy = true;
        }
        $info['vip_price'] = floor($info['price'] * config('app.vipDis'));
        unset($info->netdisk);
        unset($info->extracted_code);
        unset($info->jiangkuaihe);
        unset($info->institution_avatar_id);
        $info['commentCount'] = $this->getCommentCount($params['id']);
        return result()->success($info);
    }
    protected function getCommentCount($photoId)
    {
        $commentSql = new CommentModel();
        $count = $commentSql
            ->where('exchangeId', $photoId)
            ->where('type', 4)
            ->count();
        return $count;
    }
    public function detailView()
    {
        $params = $this->request->post(['id']);
        $sql = new PhotoListModal();
        $sql->where('id', $params['id'])
            ->inc('view')
            ->update();
        return result()->onlySucMsg("增加成功");
    }
    public function allImgList(Request $request)
    {
        $params = $this->request->post(['id']);
        $sql = new PhotoListModal();
        $info = $sql->find($params['id']);
        if($info->price == 0) {
            return $this->buyImgList(true);
        }
        if(!empty($request->user)) {
            $isBuy = $request->user->checkBuyPhoto($params['id']);
            if($isBuy) {
                return $this->buyImgList(true);
            }
        }
        return $this->noBuyImgList();
    }
    public function imgList(Request $request)
    {
        $params = $this->request->post(['id']);
        $sql = new PhotoListModal();
        $info = $sql->find($params['id']);
        if($info->price == 0) {
            return $this->buyImgList();
        }
        if(!empty($request->user)) {
            $isBuy = $request->user->checkBuyPhoto($params['id']);
            if($isBuy) {
                return $this->buyImgList();
            }
        }
        return $this->noBuyImgList();
    }

    private function noBuyImgList()
    {
        $params = $this->request->post(['id']);
        $photoSql = new PhotoListModal();
        $photoInfo = $photoSql->where('id', $params['id'])->findOrEmpty();
        if ($photoInfo->isEmpty()) {
            return result()->fail("图集不存在", 400);
        }
        $sql = new PohtoListImage();
        $list = $sql
            ->where('photo_id', $params['id'])
            ->order('sort asc')
            ->order('create_at asc')
            ->page(1)
            ->limit($this->feeNum)
            ->select();
        if(config('app.imgtype') == 'local') {
            foreach ($list as $k => $item) {
                $item['image_url'] = $item['image_path'];
            }
        }
        return result()->success($list);
    }
    private function buyImgList($all = false)
    {
        $params = $this->request->post(['current', 'size', 'id']);
        $sql = new PohtoListImage();
        if($all) {
            $list = $sql
                ->where('photo_id', $params['id'])
                ->order('sort asc')
                ->order('create_at asc')
                ->select();
        } else {
            $list = $sql
                ->where('photo_id', $params['id'])
                ->order('sort asc')
                ->order('create_at asc')
                ->page($params['current'])
                ->limit($params['size'])
                ->select();
        }
        if(config('app.imgtype') == 'local') {
            foreach ($list as $k => $item) {
                $item['image_url'] = $item['image_path'];
            }
        }
        return result()->success($list);
    }

    /**
     *  购买模块
     */
    public function buy(Request $request)
    {
        $params = $this->request->post(['id']);
        $photoSql = new PhotoListModal();
        $whereArr[] = ['id', '=', $params['id']];
        $photoInfo = $photoSql->where($whereArr)->findOrEmpty();
        if ($photoInfo->isEmpty()) {
            return result()->fail("图集不存在", 400);
        }
        if($photoInfo->private == 1) {
            return result()->fail("资源被举报已下架", 400);
        }
        if($request->user->user_type == 'VIP') {
            $price = floor($photoInfo->price * config('app.vipDis'));
        } else {
            $price = $photoInfo->price;
        }
        if($price > $request->user->integral) {
            return result()->fail("软妹币不足", 400);
        }
        Db::startTrans();
        try {
            $sql = new PhotoBuyModal();
            $sql->save([
                'photo_id' => $params['id'],
                'userid' => $request->user->id,
                'price' => $price,
            ]);
            $userLog = new Interal($request->user->id,'BUY_PHOTO');
            $userLog->setNum(-$price);
            $userLog->setContent("购买图集");
            $userLog->setAboutId($params['id']);
            $userLog->save();
            $sellUserLog = new Interal($photoInfo->releaseid,'SELL_PHOTO');
            $sellUserLog->setNum($photoInfo->price);
            $sellUserLog->setContent("出售图集");
            $sellUserLog->setAboutId($params['id']);
            $sellUserLog->save();
            Db::commit();
            return result()->onlySucMsg("购买成功");
        }   catch (\Throwable $th) {
            Db::rollback();
            return result()->fail($th->getMessage(), 500);
        }
    }

    public function buyPhotoList(Request $request)
    {
        $params = $this->request->post(['current', 'size', 'keyword', 'type_id', 'author_id', 'institution_id', 'tags', 'startTime', 'endTime']);
        $sql = new PhotoBuyModal();
        $whereArr[] = ['userid', '=', $request->user->id];
        // $params['startTime'] = '2021-01-01';
        // $params['endTime'] = '2021-12-31';
        if(isset($params['startTime']) && $params['startTime']) {
            $startTime = strtotime($params['startTime']);
            $infoWhereArr[] = ['create_at', '>=', $startTime];
        }
        if(isset($params['endTime']) && $params['endTime']) {
            $endTime = strtotime($params['endTime']);
            $infoWhereArr[] = ['create_at', '<=', $endTime];
        }
        $infoWhereArr[] = ['delete_at', '=', null];
        $whereOr = [];
        if(isset($params['type_id']) && $params['type_id']) {
            $infoWhereArr[] = ["type_id", "=", $params['type_id']];
        }
        if(isset($params['author_id']) && $params['author_id']) {
            $infoWhereArr[] = ['author_id', '=', $params['author_id']];
        }
        if(isset($params['keyword']) && $params['keyword']) {
            $infoWhereArr[] = ["name", "LIKE", '%'.$params['keyword'].'%'];
        }
        if(isset($params['tags']) && $params['tags']) {
            foreach($params['tags'] as $item){
                $whereOr[] = ["tags", "find in set", $item];
            }
        }
        $condition = count($infoWhereArr) + count($whereOr) > 0;
        $list = $sql
            ->where($whereArr)
            ->when($condition, function ($query) use($infoWhereArr, $whereOr) {
                $query->hasWhere('info', $infoWhereArr);
            })
            ->page($params['current'])
            ->limit($params['size'])
            ->with(['info', 'tags'])
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })
            ->order('create_at desc')
            ->select();
        $total = $sql
            ->where($whereArr)
            ->when($condition, function ($query) use($infoWhereArr, $whereOr) {
                $query->hasWhere('info', $infoWhereArr);
            })->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })->count();
        foreach ($list as $key => $value) {
            $value['info']['vip_price'] = floor($value['info']['price'] * config('app.vipDis'));
            if(config('app.imgtype') == 'local') {
                $value['info']['image_url'] = $value['info']['image_path'];
            }
            $value['info']['orderno'] = $value['id'];
            $list[$key] = $value['info'];
        }
        return result()->success([
            'data' => $list,
            'total' => $total
        ]);
    }
    /**
     *  点赞模块
     */
    public function like(Request $request){
        $params = $this->request->post(['id']);
        $sql = new PhotoLikeModal();
        $whereArr[] = ['photo_id', '=', $params['id']];
        $whereArr[] = ['userid', '=', $request->user->id];
        $info = $sql->where($whereArr)->findOrEmpty();
        if(!$info->isEmpty()) {
            $info->delete();
            return result()->onlySucMsg("取消点赞成功");
        }
        $sql->save([
            'photo_id' => $params['id'],
            'userid' => $request->user->id,
        ]);
        return result()->onlySucMsg("点赞成功");
    }
    /**
     *  收藏模块
     */
    public function collWork()
    {
        $sql = new PhotoCollWork();
        $list = $sql->where('userid', $this->request->user->id)->with('url')->withCount(['coll'])->select();
        return result()->success($list);
    }
    public function addWork()
    {
        $sql = new PhotoCollWork();
        $params = $this->request->post(['name', 'description']);
        $sql->save([
            'name' => $params['name'],
            'description' => $params['description'],
            'userid' => $this->request->user->id,
        ]);
        return result()->onlySucMsg("添加成功");
    }
    public function editWork()
    {
        $sql = new PhotoCollWork();
        $params = $this->request->post(['id', 'name', 'description']);
        $info = $sql->where('id', $params['id'])->where('userid', $this->request->user->id)->findOrEmpty();
        if($info->isEmpty()) {
            return result()->fail("文件夹不存在", 400);
        }
        $info->save([
            'name' => $params['name'],
            'description' => $params['description'],
        ]);
        return result()->onlySucMsg("修改成功");
    }
    public function delWork()
    {
        $sql = new PhotoCollWork();
        $params = $this->request->post(['id']);
        $info = $sql->where('id', $params['id'])->where('userid', $this->request->user->id)->findOrEmpty();
        if($info->isEmpty()) {
            return result()->fail("文件夹不存在", 400);
        }
        $info->delete();
        return result()->onlySucMsg("删除成功");
    }
    public function coll(Request $request)
    {
        $params = $this->request->post(['id', 'work_id']);
        $sql = new PhotoCollModal();
        $whereArr[] = ['photo_id', '=', $params['id']];
        $whereArr[] = ['userid', '=', $request->user->id];
        $info = $sql->where($whereArr)->findOrEmpty();
        if(!$info->isEmpty()) {
            $info->delete();
            return result()->onlySucMsg("取消收藏成功");
        }
        $sql->save([
            'photo_id' => $params['id'],
            'work_id' => $params['work_id'],
            'userid' => $request->user->id,
        ]);
        return result()->onlySucMsg("收藏成功");
    }

    public function collList()
    {
        $params = $this->request->post(['current', 'size', 'work_id', 'type_id', 'author_id', 'institution_id', 'keyword', 'tags']);
        $sql = new PhotoCollModal();
        $whereArr[] = ['userid', '=', $this->request->user->id];
        if(isset($params['work_id']) && $params['work_id']) {
            $whereArr[] = ["work_id", "=", $params['work_id']];
        }
        $infoWhereArr[] = ['private', '=', 0];
        $whereOr = [];
        if(isset($params['type_id']) && $params['type_id']) {
            $infoWhereArr[] = ["type_id", "=", $params['type_id']];
        }
        if(isset($params['keyword']) && $params['keyword']) {
            $infoWhereArr[] = ["name", "LIKE", '%'.$params['keyword'].'%'];
        }
        if(isset($params['tags']) && $params['tags']) {
            foreach($params['tags'] as $item){
                $whereOr[] = ["tags", "find in set", $item];
            }
        }
        $condition = count($infoWhereArr) + count($whereOr) > 0;
        $list = $sql
            ->where($whereArr)
            ->when($condition, function ($query) use($infoWhereArr) {
                $query->hasWhere('info', $infoWhereArr);
            })
            ->page($params['current'])
            ->limit($params['size'])
            ->with(['info'])
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })
            ->order('create_at desc')
            ->select();
        $total = $sql
            ->where($whereArr)
            ->when($condition, function ($query) use($infoWhereArr) {
                $query->hasWhere('info', $infoWhereArr);
            })
            ->where(function ($query) use($whereOr) {
                $query->whereOr($whereOr);
            })
            ->count();
        foreach ($list as $key => $value) {
            $info = $value['info'];
            $info['vip_price'] = floor($info['price'] * config('app.vipDis'));
            if(config('app.imgtype') == 'local') {
                $info['image_url']= $info['image_path'];
            }
            $list[$key] = $info;
        }
        return result()->success([
            'data' => $list,
            'total' => $total
        ]);
    }

    public function photoUser() {
        $params = $this->request->post(['id']);
        $sql = new PohtoUserModal();
        $info = $sql->with('institutionName')->withCount('photoNum')->find($params['id']);
//        $oss = new OssService();
//        $info['avatar'] = $oss->signId($info['avatar_id']);
        return result()->success($info);
    }


    public function photoReplyUser(Request $request) {
        $params = $this->request->post(['id']);
        $sql = new UserModel();
        $info = $sql->withCount('photoNum')->find($params['id']);
        if(empty($request->user)) {
            $info['is_follow'] = false;
        } else {
            $followsql = new FollowModal();
            $count = $followsql->where('userid', $request->user->id)->where('follow_id', $params['id'])->count();
            $info['is_follow'] = $count > 0;
        }

        // 删除password
        unset($info['password']);
        unset($info['integral']);
        unset($info['comment_bg_id']);
        unset($info['childerIntegral']);
        unset($info['cellphone']);
        unset($info['birthday']);
        unset($info['fileSize']);
        unset($info['openid']);
        unset($info['superiorUserId']);
        return result()->success($info);
    }
    /**
     * 机构相关
     */
    public function institutionList()
    {
        $params = $this->request->post(['current', 'size']);
        $sql = new PohtoInstitutionModal();
        $list = $sql->order('create_at desc')
            ->page($params['current'])
            ->limit($params['size'])
            ->with(['roleTen'])
            ->withCount('role')
            ->select();
//        $oss = new OssService();
//        foreach ($list as $key => $value) {
//            $value->cover =  $oss->signId($value->cover_id);
//            foreach ($value->roleTen as $keyTwo => $item) {
//                $item->avatar = $oss->signId($item->avatar_id);
//            }
//        }
        return result()->success($list);
    }

    public function institutuibDetail()
    {
        $params = $this->request->post(['id']);
        $sql = new PohtoInstitutionModal();
        $info = $sql->where('id', $params['id'])->withCount('role')->find();
//        $oss = new OssService();
//        $info->cover =  $oss->signId($info->cover_id);
        return result()->success($info);
    }

    /**
     * 角色相关
     */
    public function roleList()
    {
        $params = $this->request->post(['current', 'size', 'institution_id', 'keyword']);
        $whereArr = [];
        if(isset($params['institution_id']) && $params['institution_id']) {
            $whereArr[] = ['institution_id', '=', $params['institution_id']];
        }
         if(isset($params['keyword']) && $params['keyword']) {
             $whereArr[] = ["username", "LIKE", '%'.$params['keyword'].'%'];
             $log = new SearchLogModal();
             $logInfo = $log->where('text', $params['keyword'])->findOrEmpty();
             if($logInfo->isEmpty()) {
                 $log->save([
                     'text' => $params['keyword'],
                     'count' => 1
                 ]);
             } else {
                 $logInfo->count = $logInfo->count + 1;
                 $logInfo->save();
             }
         }
        $sql = new PohtoUserModal();
        $list = $sql
            ->where($whereArr)
            ->order('create_at desc')
            ->with('photoTen')
            ->withCount('photo')
            ->page($params['current'])
            ->limit($params['size'])
            ->select();
        $oss = new OssService();
        return result()->success($oss->signIds($list, 'avatar_id', 'avatar'));
    }

    public function isUser()
    {
        /**
         * 机构内是否存在角色
         */
        $params = $this->request->post(['institution_id', 'author_id']);
        $whereArr[] = ['institution_id', '=', $params['institution_id']];
        $whereArr[] = ['id', '=', $params['author_id']];
        $sql = new PohtoUserModal();
        $count = $sql->where($whereArr)->count();
        return result()->success($count > 0);
    }

    public function tagList()
    {
        $sql = new PohtoTagModal();
        $list = $sql->orderRaw("rand() , id DESC")->limit(50)->select();
        return result()->success($list);
    }

    public function allTag()
    {
        $params = $this->request->post(['keyword']);
        $whereArr = [];
        if(isset($params['keyword']) && $params['keyword']) {
            $whereArr[] = ["name", "LIKE", '%'.$params['keyword'].'%'];
        }
        $sql = new PohtoTagModal();
        $list = $sql->where($whereArr)->select();
        return result()->success($list);
    }

    public function searchList()
    {
        $sql = new SearchLogModal();
        $list = $sql->limit(50)->order('count', 'desc')->select();
        return result()->success($list);
    }
    public function doDetailInfo()
    {
        $params = $this->request->post(['id', 'extracted_code']);
        $sql = new PhotoListModal();
        $whereArr[] = ['id', '=', $params['id']];
        $whereArr[] = ['extracted_code', '=', $params['extracted_code']];
        $info = $sql->where($whereArr)->with(['userInfo'])->findOrEmpty();
        if($info->isEmpty()) {
            return result()->fail('提取码不正确', 500);
        }
        $info['buy'] = false;
        $info['coll'] = false;
        $oss = new OssService();
        $info['avatar'] = $oss->signId($info['avatar_id']);
        $imgSql = new PohtoListImage();
        $list = $imgSql
            ->where('photo_id', $info['id'])
            ->order('sort desc')
            ->order('create_at asc')
            ->select();
        $allImg = [];
        foreach ($list as $key => $item) {
            $allImg[] =  $item['image_url'];
        }
        $info['imgList'] = $allImg;
        return result()->success($info);
    }

    public function addEdit()
    {
        $params = $this->request->post(['id']);
        if (isset($params['id']) && $params['id']) {
            return $this->edit();
        }
        return $this->add();
    }

    public function add()
    {
        $params = $this->request->post(['type_id', 'book_type', 'name', 'country', 'private', 'author_id', 'tags', 'photo_count', 'video_count', 'netdisk', 'extracted_code', 'jiangkuaihe', 'zipSize', 'private', 'price', 'sort']);
        $validate = new PhotoValidate();
        if (!$validate->scene('listadd')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $params['releaseid'] = $this->request->user->id;
        $sql = new PhotoListModal();
        $info = $sql->where('name', $params['name'])->findOrEmpty();
        if (!$info->isEmpty()) {
            return result()->fail($info->id, 1);
        }
        $sql->save($params);
        return result()->success($sql->id);
    }

    public function edit()
    {
        $params = $this->request->post(['id', 'type_id', 'book_type', 'hot', 'selected', 'name', 'country', 'private', 'author_id', 'tags', 'photo_count', 'video_count', 'netdisk', 'extracted_code', 'jiangkuaihe', 'zipSize', 'price', 'sort']);
        $validate = new CommonnValidate();
        if (!$validate->scene('edit')->check($params)) {
            return result()->fail($validate->getError(), 500);
        }
        $sql = new PhotoListModal();
        $info = $sql->find($params['id']);
        if ($info->isEmpty()) {
            return result()->fail('图集不存在', 500);
        }
        if($info->releaseid != $this->request->user->id) {
            return result()->fail('无权限', 500);
        }
        $info->save($params);
        return result()->success("修改成功");
    }

    public function downZip()
    {
        $params = $this->request->get(['id', 'extracted_code']);
        $sql = new PhotoListModal();
        $whereArr[] = ['id', '=', $params['id']];
        $whereArr[] = ['extracted_code', '=', $params['extracted_code']];
        $info = $sql->where($whereArr)->findOrEmpty();
        if($info->isEmpty()) {
            return result()->fail('提取码不正确', 500);
        }
        $imgSql = new PohtoListImage();
        $list = $imgSql
            ->where('photo_id', $params['id'])
            ->order('sort desc')
            ->order('create_at asc')
            ->select();
        $imageUrls = [];
        foreach ($list as $key => $item) {
            $imageUrls[] =  $item['image_url'];
        }
        // 创建一个临时文件来存储压缩包
        $tempFile = tempnam(sys_get_temp_dir(), 'zip');
        // 实例化 ZipArchive
        $zip = new ZipArchive();
        // 打开临时文件以便写入
        if ($zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
            return Response::create('无法创建压缩文件', '404'); // 修改此处
        }
        $total = count($imageUrls);
        // 将每个图片添加到压缩包中
        foreach ($imageUrls as $index => $imageUrl) {
            $imageName = basename($imageUrl);
            $imageData = file_get_contents($imageUrl);
            if ($imageData !== false) {
                $zip->addFromString($imageName, $imageData);
            }
        }
        // 关闭压缩包
        $zip->close();
        // 读取生成的压缩文件内容为 Blob
        $zipData = file_get_contents($tempFile);
        // 删除临时文件
        unlink($tempFile);
        return download($zipData, $info['name'].'.zip', true);
    }
    private function getOrder($params)
    {
        if(isset($params['order']) && $params['order'] && $params['order'] != 'view') {
            if($params['order'] === 'create_at') {
                return [
                    'create_at' => $params['orderType'],
                    'view' => 'desc',
                    'sort' => 'desc',
                ];
            }
            $orderName = $params['order']."_count";
             return [
                $orderName => $params['orderType'],
                'view' => 'desc',
                'sort' => 'desc',
                'create_at' => 'desc',
            ];
        }
        return [
            'view' => 'desc',
            'sort' => 'desc',
            'create_at' => 'desc',
        ];
    }


}